package com.hjy.service;

import com.hjy.entity.Adcode;
import com.hjy.entity.Address;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @description
 */
public class GetCode {
    /**
     * 根据经纬度获取省市区的编码
     * @param lng 经度
     * @param lat 纬度
     * @return
     */
    public Adcode getAdcode(String lng,String lat){
        Adcode adcode=new Adcode();

        Address address=getAddress(lng,lat);
        String province=address.getProvicne();
        String city=address.getCity();
        String district=address.getDistrict();

        //获取省份的编码
        String proMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+province+"&key=dc9d0486f5a7b3bbab64de8ea705bcea");
        JSONObject proObject=JSONObject.fromObject(proMessage);
        JSONArray proArray=proObject.getJSONArray("geocodes");
        JSONObject proObject2=proArray.getJSONObject(0);
        String proCode=proObject2.getString("adcode");

        //获取市区的编码
        String cityMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+city+"&key=dc9d0486f5a7b3bbab64de8ea705bcea");
        JSONObject cityObject=JSONObject.fromObject(cityMessage);
        JSONArray cityArray=cityObject.getJSONArray("geocodes");
        JSONObject cityObject2=cityArray.getJSONObject(0);
        String cityCode=cityObject2.getString("adcode");

        //获取市区的编码
        String disMessage=getCodeResponse("https://restapi.amap.com/v3/geocode/geo?address="+district+"&key=dc9d0486f5a7b3bbab64de8ea705bcea");
        JSONObject disObject=JSONObject.fromObject(disMessage);
        JSONArray disArray=disObject.getJSONArray("geocodes");
        JSONObject disObject2=disArray.getJSONObject(0);
        String disCode=disObject2.getString("adcode");

        adcode.setProvicneCode(proCode);
        adcode.setCityCode(cityCode);
        adcode.setDistrictCode(disCode);

        return adcode;
    }

    /**
     *  根据经纬度获取省市区
     * @param lng 经度
     * @param lat 纬度
     * @return
     */
    public Address getAddress(String lng, String lat){
        Address address=new Address();
        String allMessage=getAddressResponse("https://restapi.amap.com/v3/geocode/regeo?location="+lng+","+lat+"&key=dc9d0486f5a7b3bbab64de8ea705bcea&radius=1000&extensions=all");
        JSONObject jsonObject=JSONObject.fromObject(allMessage);
        JSONObject object=jsonObject.getJSONObject("regeocode");
        JSONObject addressMessage=object.getJSONObject("addressComponent");

        String province=addressMessage.getString("province");
        String city=addressMessage.getString("city");
        String district=addressMessage.getString("district");
        String disCode=addressMessage.getString("adcode");

        address.setProvicne(province);
        address.setCity(city);
        address.setDistrict(district);

        return address;
    }
    /**
     *像高德服务发起请求，返回json格式的字符串
     * 逆地理编码
     * @param url 逆地理编码API服务地址
     * @return 返回带有省市区的参数的json格式字符串
     */
    private static String getAddressResponse(String url){
    StringBuffer result=new StringBuffer();
        try {
            URL u=new URL(url);
            URLConnection urlConnection=u.openConnection();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));

            String line;
            while ((line=bufferedReader.readLine())!=null){
                result.append(line);
            }

            bufferedReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return result.toString();
    }

    /**
     *像高德服务发起请求，返回json格式的字符串
     * 地理编码
     * @param url 地理编码API服务地址
     * @return 返回带有对应省市区编码的json格式字符串
     */
    private static String getCodeResponse(String url){
        StringBuffer result=new StringBuffer();
        try {
            URL u=new URL(url);
            URLConnection urlConnection=u.openConnection();//打开连接
            //urlConnection.getInputStream()读取连接的字节流；InputStreamReader（）将字节流转换成字符流；BufferedReader（）将字符流存到缓存区
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8"));

            String line;
            while ((line=bufferedReader.readLine())!=null){
                result.append(line);
            }

            bufferedReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

        return result.toString();
    }

}


